package com.itcast.service;

import com.itcast.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class SpringsecurityUserServoce implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    public  Map map = new HashMap();
    public void init(){
        Member member = new Member();
        member.setName("admin");
        member.setPassword(passwordEncoder.encode("admin"));
        map.put(member.getName(),member);
        Member member1 = new Member();
        member1.setName("xiaoming");
        member1.setPassword(passwordEncoder.encode("1234"));
        map.put(member1.getName(),member1);
    }
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        init();
        Member member = (Member) map.get(s);
        if (member!=null){
            List<GrantedAuthority> list = new ArrayList<>();
            list.add(new SimpleGrantedAuthority("permission_A"));
            list.add(new SimpleGrantedAuthority("permission_B"));
            if ("admin".equals(s)){
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                list.add(new SimpleGrantedAuthority("add"));
            }
            //permission_A
        User user = new User(member.getName(),member.getPassword(),list);
            return user;
        }
        return null;
    }
}
